home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_200 / 264_01 / cat.c < prev    next >
Text File  |  1980-01-01  |  2KB  |  71 lines

  1. /*
  2.  * cat - concatenate files
  3.  * Usage: cat [-] [file...]
  4.  *
  5.  * Contents of argument files are written to standard output.
  6.  * If there are no arguments, or if a file named "-" is encountered,
  7.  * standard input is written to standard output.
  8.  * Exit status is number of files that couldn't be opened or had read errors.
  9.  *
  10.  * This program is in the public domain.
  11.  * David MacKenzie
  12.  * 6522 Elgin Lane
  13.  * Bethesda, MD 20817
  14.  *
  15.  * Latest revision: 05/08/88
  16.  */
  17.  
  18. #include <stdio.h>
  19.  
  20. _main(argc, argv)
  21.     int     argc;
  22.     char  **argv;
  23. {
  24.     int     errs = 0;        /* # of files with read errors */
  25.     int     optind;        /* loop index */
  26.  
  27.     if (argc == 1)
  28.     errs += cat("-");
  29.     else
  30.     for (optind = 1; optind < argc; ++optind)
  31.         errs += cat(argv[optind]);
  32.  
  33.     exit(errs);
  34. }
  35.  
  36. /*
  37.  * Send the contents of file to standard output with no translation.
  38.  * If file is "-", use standard input, and if input is from con:,
  39.  * do newline and ^Z translation.
  40.  * Return 0 if ok, 1 if error.
  41.  */
  42.  
  43. cat(file)
  44.     char   *file;
  45. {
  46.     FILE   *fp;            /* input file pointer */
  47.     int     c;            /* one byte of input */
  48.  
  49.     if (!strcmp(file, "-")) {
  50.     /* Agetc and aputc translate cr-lf to lf and ^Z to EOF. */
  51.     if (isatty(0))
  52.         while ((c = agetc(stdin)) != EOF)
  53.         aputc(c, stdout);
  54.     else
  55.         while ((c = getc(stdin)) != EOF)
  56.         putc(c, stdout);
  57.     } else {
  58.     if ((fp = fopen(file, "r")) == NULL) {
  59.         perror(file);
  60.         return 1;
  61.     }
  62.     while ((c = getc(fp)) != EOF)
  63.         putc(c, stdout);
  64.     if (fclose(fp) == EOF) {
  65.         fprintf(stderr, "%s: Read error\n", file);
  66.         return 1;
  67.     }
  68.     }
  69.     return 0;
  70. }
  71.